package com.junxonline.instant.terminal.listener;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.reflect.TypeToken;
import com.junxonline.instant.common.constant.TerminalCommandMqConstant;
import com.junxonline.instant.common.util.terminal.NettyChannelUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;

/**
 * RocketMq拉取指令消费者
 *
 * @author JunX
 * @date 2022-05-26
 */
@Log4j2
@Component
@Transactional
@RocketMQMessageListener(consumerGroup = TerminalCommandMqConstant.GROUP_QUERY_COMMAND, topic = TerminalCommandMqConstant.TOPIC_QUERY_COMMAND)
public class TerminalQueryCommandListener implements RocketMQListener<MessageExt> {

    /**
     * 消息解析与发送
     *
     * @param message 消息内容
     */
    @Override
    public void onMessage(MessageExt message) {
        String topic = message.getTopic();
        String tags = message.getTags();
        String body = new String(message.getBody());
        // 解析
        HashMap<String, Object> data = JSON.parseObject(body, new TypeToken<HashMap<String, Object>>() {}.getType());
        log.info("TerminalQueryCommandListener接收到消息 -> topic={}, tags={}, 消息内容={}", topic, tags, body);
        if (data != null) {
            String terminalCode = (String) data.get("terminalCode");
            JSONObject msg = (JSONObject) data.get("msg");
            if (StrUtil.isNotBlank(terminalCode)) {
                log.info("Netty已发送消息 终端编号->{} 消息内容->{}", terminalCode, msg.toJSONString());
                NettyChannelUtils.sendSingleMessage(terminalCode, msg.toJSONString());
            }
        }
    }

}
